import { defineComponent, PropType, reactive, computed, ref } from 'vue'
import { State, AxiosFunction, Pagination, SetApi, Record } from './data'
export default defineComponent({
  props: {
    api: {
      type: Function as PropType<AxiosFunction>,
      required: true
    },
    params: {
      type: Object as PropType<any>,
      default: {}
    },
    setApi: {
      type: Object as PropType<SetApi>,
      required: false
    },
    delApi: {
      type: Function as PropType<AxiosFunction>,
      required: false
    }

  },
  emits: ['list'],
  setup (props, { emit, slots, attrs }) {
    const state:State = reactive({
      dataSource: [],
      loading: false,
      pageNum: 1,
      pageSize: 10,
      totalCount: 0
    })
    // 接口
    const getList = async (first?:boolean) => {
      if (first) {
        state.pageSize = 10
        state.pageNum = 1
      }
      const query = {
        pageSize: state.pageSize,
        pageNum: state.pageNum,
        ...props.params
      }
      state.loading = true
      try {
        const { data } = await props.api(query)
        if (Array.isArray(data)) {
          state.dataSource = data
        } else {
          state.dataSource = data?.list
          state.totalCount = data?.page?.totalCount
        }
      } finally {
        state.loading = false
      }
    }
    // 翻页
    const handleChange = (page: Pagination) => {
      const { current: pageNum, pageSize } = page as any
      state.pageNum = pageNum
      state.pageSize = pageSize
      getList()
    }
    const handleDel = async (id: number) => {
      await props.delApi?.({ id })
      getList()
    }
    const setStatus = async (record: Record) => {
      const url = record.isDeleted ? props?.setApi?.enable : props?.setApi?.disable
      if (!url) return
      try {
        if (record.disabled) return
        record.disabled = true
        await url({ id: record.id })
        record.isDeleted = !record.isDeleted
      } finally {
        record.disabled = false
      }
    }
    const operationSlot = (
      {
        operation: (row:any) => (
          <>
            {row.record.isDefault ? '--' : slots.operation?.(row) }
            {props.setApi && !row.record.isDefault
              ? (<a-popconfirm
              title={row.record.isDeleted ? '启用' : '停用'}
              onConfirm={() => setStatus(row.record)}
            >
              <a class="ml-20">{row.record.isDeleted ? '启用' : '停用'}</a>
            </a-popconfirm>)
              : ''}
            {props.delApi && !row.record.isDefault
              ? (<a-popconfirm
              title={'确定删除？'}
              onConfirm={() => handleDel(row.record.id)}
            >
              <a class="ml-20">删除</a>
            </a-popconfirm>)
              : ''}
          </>
        )
      }
    )
    getList()
    emit('list', getList)
    const defaultExpandAllRows = computed(() => attrs['default-expand-all-rows'])
    const renderTable = (key?:number|undefined) => {
      // 暂未找到不加key好的方案
      return <a-table dataSource={state.dataSource} key={key} v-slots={{ ...slots, ...operationSlot }} pagination={{
        total: state.totalCount,
        current: state.pageNum,
        pageSize: state.pageSize
      }} onChange={handleChange} loading={state.loading} {...attrs} defaultExpandAllRows={defaultExpandAllRows.value}/>
    }
    const renderExpandTable = () => {
      if (
        attrs['default-expand-all-rows']
      ) {
        return renderTable(Date.now())
      } else {
        return renderTable()
      }
    }
    return () => {
      return (
        renderExpandTable()
      )
    }
  }
})
